import { useReducer } from 'react';
/**
 * 定义初始状态信息
 * @loading 加载标记
 */
export interface IstateType {
  loading: boolean;
  leftSelectRows: Record<string, any>[];
  leftSelectKeys: string[]
  leftExpandedKeys: string[]
  leftAutoExpandParent: boolean
}

/**
 * 新增和编辑页面操作枚举
 * @UPDATE_ADD 新增
 * @UPDATE_EDIT 编辑
 * @UPDATE_CANCEL 作废
 * @LEFTSELECT_ROW 左侧树 选中的数据
 * @LEFTSELECT_KEYS 左侧树 选中的key
 * @LEFTEXPANDED_KEYS 左侧树 展开的节点 key
 * @LEFTAUTO_PARENT 左侧树 控制是否展开树节点
 * @CLEAR_RECEIVE 取消modal框,清空存入的接收部门数据
 * 
 */
export enum IActionEnum {
  UPDATE_ADD = 'add',
  UPDATE_EDIT = 'edit',
  UPDATE_CANCEL = 'cancel',
  LEFTSELECT_ROW = 'leftSelectRows',
  LEFTSELECT_KEYS = 'leftSelectKeys',
  LEFTEXPANDED_KEYS = 'leftExpandedKeys',
  LEFTAUTO_PARENT = 'leftAutoExpandParent',
  CLEAR_RECEIVE = "clearAllReceive"
}

/**
 * 定义新增和编辑页面操作匹配
 * @type 操作类型
 * @payload 传递数据
 */
export interface IActionType {
  type: IActionEnum;
  payload?: any;
}

/** 定义公告新增和编辑状态管理 */
export const useUpdateReducer = () => {
  /** 初始化状态 */
  const initState: IstateType = {
    loading: false,
    leftSelectRows: [],
    leftSelectKeys: [],
    leftExpandedKeys: [],
    leftAutoExpandParent: false,
  };

  /** 状态管理逻辑处理 */
  const updateReducer = (state: IstateType, action: IActionType) => {
    switch (action?.type) {
      case IActionEnum.UPDATE_ADD:
        return {
          ...state,
          loding: action?.payload,
        };
      case IActionEnum.UPDATE_EDIT:
        return {
          ...state,
          loading: action?.payload,
        };
      case IActionEnum.UPDATE_CANCEL:
        return {
          ...state,
          loading: action?.payload,
        };
      /**
       * 左侧树选中的数据
       */
      case IActionEnum.LEFTSELECT_ROW:
        return {
          ...state,
          leftSelectRows: action?.payload,
        };

      /**
       * 左侧树选中的数据的key
       */
      case IActionEnum.LEFTSELECT_KEYS:
        return {
          ...state,
          leftSelectKeys: action?.payload,
        };

      /**
       * 左侧树 展开节点 key
       */
      case IActionEnum.LEFTEXPANDED_KEYS:
        return {
          ...state,
          leftExpandedKeys: action?.payload,
        };

      /**
       * 左侧树 控制是否展开节点
       */
      case IActionEnum.LEFTAUTO_PARENT:
        return {
          ...state,
          leftAutoExpandParent: action?.payload,
        };

      /**
       * 关闭接收部门modal,清空已选数据
       */
      case IActionEnum.CLEAR_RECEIVE:
        return {
          ...state,
          leftSelectRows: [],
          leftSelectKeys: [],
          leftExpandedKeys: [],
          leftAutoExpandParent: false,
        };

      default:
        return {
          ...state,
          ...initState,
        };
    }
  };

  const [state, dispatch] = useReducer(updateReducer, initState);

  return {
    ...state,
    dispatch,
  };
};
